package com.ourteam.frame.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.frame.web.AbstractSearchHelper;
import com.ourteam.frame.web.AbstractSearchModel;
import com.ourteam.frame.web.DataAccessHelper;

import net.dao.BaseQueryBean;
import net.dao.IDataAccessInterface;

public abstract class AbstractDAOServiceController<D, Q extends BaseQueryBean>
		extends AbstractQueryServiceController<Q> {

	private DataAccessHelper<D, Q, AbstractSearchModel<Q>> dataAccessHelper = new DataAccessHelper(getDAOClass());

	public AbstractDAOServiceController() {
		super();
		ConvertUtils.register(new DateConverter(null), java.util.Date.class);
	}

	@Override
	protected AbstractSearchHelper<Q, AbstractSearchModel<Q>> getDataAccessHelper(AbstractSearchModel<Q> searchModel) {

		dataAccessHelper.setSearchModel(searchModel);

		return dataAccessHelper;
	}

	@RequestMapping("/addNew")
	@ResponseBody
	public D addNew(final @RequestParam Map<String, Object> object, HttpServletRequest request, Model model)
			throws Exception {

		D dataObj = dataAccessHelper.newDataObject();

		BeanUtils.populate(dataObj, object);

		dataAccessHelper.addNew(dataObj);

		return dataObj;

	}

	@RequestMapping("/modify")
	@ResponseBody
	public D modify(final @RequestParam Map<String, Object> object, HttpServletRequest request, Model model)
			throws Exception {

		D dataObj = dataAccessHelper.newDataObject();

		BeanUtils.populate(dataObj, object);

		dataAccessHelper.modify(dataObj);

		return dataObj;

	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public D delete(final @RequestParam Map<String, Object> object, HttpServletRequest request, Model model)
			throws Exception {

		D dataObj = dataAccessHelper.newDataObject();

		BeanUtils.populate(dataObj, object);

		dataAccessHelper.delete(dataObj);

		return dataObj;

	}

	abstract protected Class<? extends IDataAccessInterface<?, Q>> getDAOClass();

}
